package game.display;

import java.util.HashMap;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.sampled.AudioFormat;

import game.MainController;
import game.Input.EventSound;
import game.sound.MidiPlayer;
import game.sound.Sound;
import game.sound.SoundManager;

public class SoundController {
	private Queue<EventSound> eventSoundBuffer;
	private MidiPlayer midiPlayer;
	private Sequence sequence;
	private HashMap<String,Sound> sounds;
	private SoundManager soundManager;
	
	private static final int DRUM_TRACK = 1;
	// uncompressed, 44100Hz, 16-bit, mono, signed, little-endian
    private static final AudioFormat PLAYBACK_FORMAT = new AudioFormat(44100, 16, 1, true, false);
	
	public SoundController(HashMap<String, Sound> hashMap, SoundManager soundManager){
		eventSoundBuffer = new LinkedBlockingQueue<EventSound>();
		midiPlayer = new MidiPlayer();
		sequence = midiPlayer.getSequence("/sounds/BackgroundMusic.mid");
		sounds = hashMap;
		this.soundManager = soundManager;
	}
	
	public MidiPlayer getMidiPlayer(){
		return midiPlayer;
	}
	
	public void startMidiPlayer(){		
		midiPlayer.play(sequence, true);
	}
	
	public void stopMidi(){
		midiPlayer.stop();
	}
	
	public void clearEventSoundBuffer(){
		eventSoundBuffer.clear();
	}

	public void executeEventSoundBufferedActions() {
		while (!eventSoundBuffer.isEmpty()) {
			executeEventSoundAction(eventSoundBuffer.poll());
		}
	}

	private void executeEventSoundAction(EventSound sound) {
		switch(sound){
		case POWERUP:
			soundManager.play(sounds.get("pickupSound"));
			break;
		case HIT:
			soundManager.play(sounds.get("hitSound"));
			break;
		}
	}
	
	public void addEventSoundAction(EventSound eventSound) {
		eventSoundBuffer.add(eventSound);
	}

	public void stop() {
		midiPlayer.stop();
		soundManager.join();
	}
	
	public HashMap<String, Sound> getSounds(){
		return sounds;
	}
	
	public SoundManager getSoundManager(){
		return soundManager;
	}
}
